package com.yilin.tms.order.service.payment.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.utils.QueryUtil;
import com.yilin.tms.core.entity.capital.TradeRecord;
import com.yilin.tms.core.entity.order.clearing.ClearingDetail;
import com.yilin.tms.core.entity.order.payment.OrderSettlementCost;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.user.RoleType;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.order.mapper.payment.OrderSettlementCostMapper;
import com.yilin.tms.order.service.payment.IOrderSettlementCostService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderSettlementCostService extends ServiceImpl<OrderSettlementCostMapper, OrderSettlementCost> implements IOrderSettlementCostService {

    @Resource
    private OrderSettlementCostMapper orderSettlementCostMapper;

    /**
     * 通知支付结果，重复通知无效
     * 通知结果只更新状态
     * */
    @Override
    public void updateOrderSettlementResult(TradeRecord tradeRecord, Account loginUser){
        List<TradeRecord.TradeStatus> statusList = ArrayUtil.initList(TradeRecord.TradeStatus.paySuccess, TradeRecord.TradeStatus.payFail, TradeRecord.TradeStatus.create, TradeRecord.TradeStatus.close);
        if (!statusList.contains(tradeRecord.getTradeStatus())) throw new BusinessException("结算支付结果状态有误！");
        String [] orderPaymentIds = tradeRecord.getOrderPaymentIds().split(",");
        List<OrderSettlementCost> settlementCostList = orderSettlementCostMapper.selectBatchIds(ArrayUtil.initList(orderPaymentIds));
        settlementCostList.forEach(settlementPayment -> {
            if (settlementPayment.getPayStatus() == OrderSettlementCost.PayStatus.success) throw new BusinessException("订单已经支付完成...");
            /// 分别在成功，创建，关闭+失败时更新状态
            if (tradeRecord.getTradeStatus()==TradeRecord.TradeStatus.paySuccess){
                settlementPayment.setBankFlowNo(tradeRecord.getBankFlowNo());
                settlementPayment.setPayCompleteTime(tradeRecord.getFinishTime());
                settlementPayment.setPayStatus(OrderSettlementCost.PayStatus.success);
                settlementPayment.setPaymentTypeName(tradeRecord.getPayType().name+tradeRecord.getBankType().name);
                settlementPayment.setPaymentCapitalAccount(tradeRecord.getPaymentCapitalAccount());
                settlementPayment.setIncomeCapitalAccount(tradeRecord.getIncomeCapitalAccount());
                settlementPayment.setOptUserId(tradeRecord.getOptUserId());
                settlementPayment.setOptUserName(tradeRecord.getOptUserName());
                settlementPayment.setBankFlowNo(tradeRecord.getBankFlowNo());
            } else if (tradeRecord.getTradeStatus() == TradeRecord.TradeStatus.create){
                settlementPayment.setPayStatus(OrderSettlementCost.PayStatus.wait);
                settlementPayment.setInitiateUserId(loginUser==null?null:loginUser.getId());
                settlementPayment.setInitiateUserName(loginUser==null?null:loginUser.getName());
                settlementPayment.setTradeNo(tradeRecord.getTradeNo());
            } else {//失败/关闭时，恢复预支付单状态
                settlementPayment.setPayStatus(OrderSettlementCost.PayStatus.approved);
                settlementPayment.setTradeNo(null);
            }
            orderSettlementCostMapper.updateById(settlementPayment);
        });
    }

    /**
     * 生成结款单
     * 结款单基于清算明细生成
     * */
    @Override
    public OrderSettlementCost generateOrderSettlement(TransitOrder transitOrder, ClearingDetail clearingDetail){
        OrderSettlementCost orderSettlementCost = getOrderSettlementCostByTransitOrderId(transitOrder.getId());
        if (orderSettlementCost!=null) return orderSettlementCost;
        //-创建信息支付单
        orderSettlementCost = new OrderSettlementCost();
        orderSettlementCost.setPrePaymentNo(DateTimeUtil.dateNo("YF"));
        orderSettlementCost.setClearOrderId(clearingDetail.getId());
        orderSettlementCost.setTransitOrderId(transitOrder.getId());
        orderSettlementCost.setTransportNo(transitOrder.getTransportNo());
//        orderSettlementCost.setPlatId(transitOrder.getPlatId());
//        orderSettlementCost.setPlatName(transitOrder.getPlatName());
//        orderSettlementCost.setZonePlatId(transitOrder.getZonePlatId());
//        orderSettlementCost.setZonePlatName(transitOrder.getZonePlatName());
        orderSettlementCost.setTruckerOrganizeId(transitOrder.getRobOrganizeId());
        orderSettlementCost.setTruckerOrganizeName(transitOrder.getRobOrganizeName());
        orderSettlementCost.setTruckNo(transitOrder.getTransitTruckNo());
        orderSettlementCost.setTruckerUserName(transitOrder.getTransitTruckUserName());
        //-记录费用
        orderSettlementCost.setActualTransportCost(clearingDetail.getShipperTransportCost());
        orderSettlementCost.setAdditionalCost(clearingDetail.getAdditionalCost());
        orderSettlementCost.setTruckerFeeCost(clearingDetail.getTruckerFeeCost());
        orderSettlementCost.setDiffIndemnityCost(clearingDetail.getDiffIndemnityCost());
        orderSettlementCost.setOilCost(clearingDetail.getOilCost());
        orderSettlementCost.setEtcTollCost(clearingDetail.getEtcTollCost());
        orderSettlementCost.setAddedTaxCost(clearingDetail.getAddedTaxCost());
        orderSettlementCost.setCityTaxCost(clearingDetail.getCityTaxCost());
        orderSettlementCost.setLocalEduTaxCost(clearingDetail.getLocalEduTaxCost());
        orderSettlementCost.setEduAddTaxCost(clearingDetail.getEduAddTaxCost());
        orderSettlementCost.setIncomeTaxCost(clearingDetail.getIncomeTaxCost());
        orderSettlementCost.setTruckerTaxCost(clearingDetail.getTruckerTaxCost());//稅費合計
        orderSettlementCost.setTechnicalFeeCost(clearingDetail.getTechnicalFeeCost());
        orderSettlementCost.setSettlementCost(clearingDetail.getTruckerActualIncomeCost());
        //--
        orderSettlementCost.setPayCreateTime(new Date());
        orderSettlementCost.setPayStatus(OrderSettlementCost.PayStatus.approved);
        orderSettlementCostMapper.insert(orderSettlementCost);
        return orderSettlementCost;
    }

    @Override
    public OrderSettlementCost getOrderSettlementCostByTransitOrderId(String transitOrderId){
        QueryWrapper<OrderSettlementCost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transit_order_id", transitOrderId);
        return orderSettlementCostMapper.selectOne(queryWrapper);
    }

    @Override
    public PageData<OrderSettlementCost> getOrderSettlementPage(OrderSettlementCost query, Account loginUser, Integer page, Integer limit) {
        QueryWrapper<OrderSettlementCost> queryWrapper = new QueryWrapper<>();
//        if (loginUser.getUserType() != UserType.adminUser && loginUser.getUserType() != UserType.yilinUser) {
//            if (loginUser.getUserType()== UserType.zoneUser){
//                queryWrapper.eq("zone_plat_id", loginUser.getOrganizeId());
//            } else if (loginUser.getUserType()== UserType.platformUser){
//                queryWrapper.eq("plat_id",loginUser.getOrganizeId());
//            } else {
//                if(loginUser.getRoleType() == RoleType.manager) queryWrapper.eq("trucker_organize_id",loginUser.getOrganizeId() );
//                else queryWrapper.eq("trucker_account_id",loginUser.getId() );
//            }
//        }
        return orderSettlementCostMapper.selectPage(new PageData<>(page,limit), QueryUtil.andQueryWrapper(queryWrapper,query));
    }

    @Override
    public List<OrderSettlementCost> getOrderSettlementListByIds(List<String> orderSettlementIds) {
        return orderSettlementCostMapper.selectBatchIds(orderSettlementIds);
    }

    @Override
    public List<OrderSettlementCost> getOrderSettlementListByTransOrderIds(List<String> transOrderIdList) {
        QueryWrapper<OrderSettlementCost> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("transit_order_id", transOrderIdList);
        return orderSettlementCostMapper.selectList(queryWrapper);
    }

}
